package xyz.yuzegod.megawalls.database;

import org.bukkit.configuration.ConfigurationSection;
import xyz.yuzegod.megawalls.MegaWalls;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;

public class MySQLCore extends DataBaseCore
{
    private static String driverName;
    private static Logger logger;
    private String username;
    private String password;
    private Connection connection;
    private String url;
    
    public MySQLCore(final ConfigurationSection cfg) {
        this(cfg.getString("ip"), cfg.getInt("port"), cfg.getString("database"), cfg.getString("username"), cfg.getString("password"),cfg.getBoolean("forceunicode"));
    }
    
    public MySQLCore(final String host, final int port, final String dbname, final String username, final String password,boolean forceUnicode) {
        if (forceUnicode) {
            this.url = "jdbc:mysql://" + host + ":" + port + "/" + dbname+"?useUnicode=true&characterEncoding=utf8";
        }else {
            this.url = "jdbc:mysql://" + host + ":" + port + "/" + dbname;
        }
        this.username = username;
        this.password = password;
        try {
            Class.forName(MySQLCore.driverName).newInstance();
        }
        catch (Exception e) {
            MySQLCore.logger.warning("数据库初始化失败 请检查驱动 " + MySQLCore.driverName + " 是否存在!");
        }
    }
    
    @Override
    public boolean createTables(final String tableName, final KeyValue fields, final String conditions) throws SQLException {
        final String sql = "CREATE TABLE IF NOT EXISTS `" + tableName + "` ( " + fields.toCreateString() + ((conditions == null) ? "" : (" , " + conditions)) + " );";
        return this.execute(sql);
    }
    
    @Override
    public Connection getConnection() {
        try {
            if (this.connection != null && !this.connection.isClosed()) {
                return this.connection;
            }
            return this.connection = DriverManager.getConnection(this.url, this.username, this.password);
        }
        catch (SQLException e) {
            MySQLCore.logger.warning("数据库操作出错: " + e.getMessage());
            MySQLCore.logger.warning("登录URL: " + this.url);
            MySQLCore.logger.warning("登录账户: " + this.username);
            MySQLCore.logger.warning("登录密码: " + this.password);
            return null;
        }
    }
    
    static {
        MySQLCore.driverName = "com.mysql.jdbc.Driver";
        MySQLCore.logger = MegaWalls.getInstance().getLogger();
    }
}
